import os
from docx import Document
import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
from flask import Flask, jsonify, request

app = Flask(__name__)

# 1. AI API 调用函数，返回功能点和描述
def call_ai_api(content):
    api_url = "https://open.bigmodel.cn/api/paas/v4/chat/completions"
    headers = {
        "Content-Type": "application/json",
        "Authorization": "103f067729ac42b2a159f9a66a281dd7.Q2IQv5mgWbidoacD"
    }
    
    # 询问AI模型提取功能点与描述
    question = f"以下这一段的软件功能点是什么？回答分为两个部分，分别为功能点和描述。描述请使用短句简要回答，先回答，\
        功能点与描述之间采用';'隔开，功能点之间采用','隔开，每个功能点需要描述其属于EI,EO,EQ,ILF,EIF之中的哪个类型\
        ，回复严格按照格式，格式为(功能点,类型)，除了功能点和描述以外不回复其他内容，回复的示例为:  描述;(功能点1，类别),(功能点2，类别):   {content}"
    
    payload = {
        "model": "chatglm_6b",
        "messages": [{"role": "user", "content": question}]
    }
    
    try:
        response = requests.post(api_url, json=payload, headers=headers)
        if response.status_code == 200:
            result = response.json()
            return result.get("choices")[0].get("message").get("content")
        else:
            print(f"API请求失败，状态码: {response.status_code}")
            return None
    except Exception as e:
        print(f"调用API时出现错误: {e}")
        return None

# 2. 解析 Word 文档
def read_and_number_headings(doc_path):
    if not os.path.exists(doc_path):
        return {}

    doc = Document(doc_path)
    heading_numbers = []  # 存储编号
    headings_dict = {}  # 存储标题和内容

    for para in doc.paragraphs:
        text = para.text.strip()
        style_name = para.style.name
        
        if "Heading" in style_name:
            heading_level = int(style_name.split(' ')[-1])  # 获取层级

            if heading_level > len(heading_numbers):
                for _ in range(heading_level - len(heading_numbers)):
                    heading_numbers.append(1)  
            elif heading_level < len(heading_numbers):
                heading_numbers = heading_numbers[:heading_level]
                heading_numbers[heading_level - 1] += 1
            else:
                heading_numbers[heading_level - 1] += 1

            heading_number = '.'.join(map(str, heading_numbers))
            headings_dict[heading_number] = {
                "title": text,
                "content": [],
                "description": None,  
                "function_point": None  # 添加function_point字段
            }
        else:
            if heading_numbers:
                heading_number = '.'.join(map(str, heading_numbers))
                headings_dict[heading_number]["content"].append(text)
    
    return headings_dict

# 3. 并行调用 AI 处理文本内容，提取功能点和描述
def process_content_with_ai(headings_dict):
    with ThreadPoolExecutor(max_workers=10) as executor:
        future_to_heading = {}

        # 提交任务
        for heading_number, heading_info in headings_dict.items():
            if heading_info["content"]:
                content = "\n".join(heading_info["content"])  # 合并所有段落
                future = executor.submit(call_ai_api, content)
                future_to_heading[future] = heading_number

        # 收集任务结果
        for future in as_completed(future_to_heading):
            heading_number = future_to_heading[future]
            description = future.result()  # 获取 AI 返回的结果
            if description:
                # 将功能点和描述提取出来
                try:
                    # 以分号分隔功能点和描述
                    description, function_point = description.split(';', 1)  # 分割功能点和描述
                    headings_dict[heading_number]["description"] = description.strip()
                    headings_dict[heading_number]["function_point"] = function_point.strip()
                except ValueError:
                    headings_dict[heading_number]["description"] = description
                    headings_dict[heading_number]["function_point"] = "无描述"
            else:
                headings_dict[heading_number]["description"] = "API 请求失败"
                headings_dict[heading_number]["function_point"] = "无描述"
    
    return headings_dict

# 4. 构建多级目录结构的 JSON 数据
def build_directory_structure(headings_dict):
    structure = {}
    
    for heading_number, heading_info in headings_dict.items():
        levels = heading_number.split('.')
        current_level = structure
        
        for level in levels:
            if level not in current_level:
                current_level[level] = {}
            current_level = current_level[level]
        
        # 将 title, content, description 和 function_point 添加到最终结构中
        current_level["title"] = heading_info['title']
        current_level["content"] = "\n".join(heading_info['content'])  # 加入原文内容
        current_level["description"] = heading_info.get("description", "无解析结果")
        current_level["function_point"] = heading_info.get("function_point", "无描述")
    
    return structure

# 5. Flask 路由返回目录结构
@app.route('/get_directory_structure', methods=['POST'])
def directory_structure():
    data = request.json
    doc_path = data.get('doc_path', '')  

    if not os.path.exists(doc_path):
        return jsonify({
            "code": 1,
            "msg": "路径不存在",
            "data": {}
        })
    
    headings_dict = read_and_number_headings(doc_path)  
    headings_dict = process_content_with_ai(headings_dict)  
    directory_structure_data = build_directory_structure(headings_dict)

    return jsonify({
        "code": 0,
        "msg": "成功",
        "data": directory_structure_data
    })

if __name__ == '__main__':
    app.run(debug=True)
